#include "sound.h"
#include <QFileInfo>
#include <QAudioOutput>

Sound::Sound(QObject *parent) : QObject(parent),player(new QMediaPlayer(this)),
    audioOutput(new QAudioOutput(this))
{
    player->setAudioOutput(audioOutput);

    // 错误处理
    connect(player, &QMediaPlayer::errorOccurred, [](auto, auto errorString){
        qWarning() << "MediaPlayer error:" << errorString;
    });
}

void Sound::playSound(const QString &filePath,bool loop) {
    if (filePath.startsWith(":")) {
        player->setSource(QUrl("qrc" + filePath));
    } else {
        if (!QFileInfo::exists(filePath)) {
            qWarning("File not found: %s", qUtf8Printable(filePath));
            return;
        }
        player->setSource(QUrl::fromLocalFile(filePath));
    }
    setLoop(loop);  // 设置循环状态
    player->play();
}
void Sound::setLoop(bool loop)
{
    m_loop = loop;
    if (player) {
        // Qt6方式设置循环
        player->setLoops(loop ? QMediaPlayer::Infinite : 1);
    }
}
// 设置音量 (范围 0.0 ~ 1.0)
void Sound::setVolume(float volume) {
    if (audioOutput) {
        // 确保音量在合理范围内
        volume = qBound(0.0f, volume, 1.0f);
        audioOutput->setVolume(volume);
    }
}

// 获取当前音量
float Sound::volume() const {
    if (audioOutput) {
        return audioOutput->volume();
    }
    return 0.0f;
}
